<?php

/**
 * Notes:WebSocket服务端
 * @Author szh
 * Class WS
 * 启动
 * php WS.php
 */
class wsChat
{
    private $ws = null;

    public function __construct()
    {
        //$this->ws = new Swoole\WebSocket\Server('0.0.0.0', 9502);
        $this->ws = new Swoole\WebSocket\Server('0.0.0.0', 9502, SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL);//
        // 后面的配置是服务器证书需要ssl
        $this->http->set([
            'ssl_cert_file'=> '/www/server/panel/xhost/cert/test.demo/xxx.pem',//SSL证书位置
            'ssl_key_file' => '/www/server/panel/xhost/cert/test.demo/xxx.pem',//SSL证书key位置

        ]);
        $this->ws->on('Open', [$this, "onOpen"]);
        $this->ws->on('Message', [$this, "onMessage"]);
        $this->ws->on('Close', [$this, "onClose"]);
        $this->ws->start();
    }
    public function onOpen($ws, $request){
        var_dump($request->fd, $request->get, $request->server);
        $ws->push($request->fd, "hello, 欢迎客户端 id：{$request->fd}\n");
    }
    public function onMessage($ws, $frame){
        echo "信息: {$frame->data}\n";
        foreach ($ws->connections as $fd){
            if($fd == $frame->fd){
                $ws->push($fd, "我: {$frame->data}");
            }else{
                $ws->push($fd, "对方: {$frame->data}");
            }
        }
        //$ws->push($frame->fd, "server: {$frame->data}");
    }
    public function onClose($ws, $fd){
        echo "客户端：{$fd} 关闭\n";
    }
}
new WS();